import { Router } from "vue-router";
import { message } from "ant-design-vue";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import store from "@/store";
import { token } from '@/util';
import { Response } from "@/types";

NProgress.configure({ showSpinner: false });

export function createRouterGuards(router: Router) {

    router.beforeEach((to, from, next) => {
        NProgress.start()
        // storage 中 token 过期 todo
        // 登录后跳转到 之前页面  todo
        const t = token.get()
        //未登录状态，访问任何页面都会到登录页
        if (!t) {
            store.dispatch('user/destorySession');
            return to.name === 'Login' ? next() : next({ name: 'Login' })
        }
        store.dispatch('user/refresh').then((res: boolean) => {
            if (res) {
                if (to.name == 'Login') {
                    next({ name: 'Home', replace: true })
                } else {
                    next()
                }
            } else {
                message.warn('登录超时，重新登录', 2).then(() => next({ name: 'Login' }), () => { })
            }
        })
    })
    router.afterEach(() => {
        NProgress.done()
    })
}


